// 插件地址：https://github.com/giantss/cordova-plugin-ImagePicker

import { prepareToDisplay, copyFile } from '@/utils/file'

const that = this

function _setOptions() {
  var options = {
    maximumImagesCount: 9, // 最多支持9张
    width: -1,
    height: -1
  }
  return options
}

function pickPhoto(id) {
  console.log('调用拍照接口，对应的工卡ID：' + id)
  return new Promise(
    (resolve, reject) => {
      const cameraOptions = _setOptions()
      // eslint-disable-next-line
      ImagePicker.getPictures(
        pictures => {
          const copyfiles = []
          console.log('[camera]-[pickPhoto]-pictures: ')
          console.log(pictures)
          pictures.images.forEach(
            picture => {
              const sourceFilePath = 'file://' + picture.path.substring(0, picture.path.lastIndexOf('/') + 1)
              const sourceFileName = decodeURI(picture.path.substring(picture.path.lastIndexOf('/') + 1, picture.path.length))
              copyfiles.push(copyFile(id, sourceFilePath, sourceFileName))
            }
          )

          resolve(Promise.all(copyfiles))
          // pictures.images.forEach(
          //   picture => {
          //     const copyfile = copyFile(picture)
          //     // prepareToDisplay(picture.path, files)

          //   }
          // )
          console.log('[pickPhoto]-files:' + JSON.stringify(copyfiles))
          // resolve(files)
          // // 把照片从临时目录拷贝到cordova.file.dataDirectory目录
          // if (pictures.images.length !== 0) {
          //   pictures.images.forEach(
          //     picture => {
          //       copyFile(picture.path)
          //     }
          //   )
          //   resolve(pictures) // 返回原始数组
          // } else {
          //   resolve([]) // 什么都不选，返回空数组
          // }
        },
        function(err) {
          console.log('调用拍照接口出现错误！' + err)
          reject(err)
          that.$message(
            {
              message: '照片选择错误！',
              type: 'error'
            }
          )
        },
        cameraOptions
      )
    }
  ).then(
    files => {
      console.log('all copied files: ')
      console.log(files)
      const fileObjs = []
      files.forEach(
        file => {
          const fileName = decodeURI(file.substring(file.lastIndexOf('/') + 1))
          console.log('Prepare to display for file: ' + fileName)
          fileObjs.push(prepareToDisplay(id, fileName))
        }
      )
      return Promise.all(fileObjs)
    }
  )
}

// function onCameraSuccess(pictures) {
//   console.log(pictures)
//   // 把照片从临时目录拷贝到cordova.file.dataDirectory目录，同时删除cache目录
//   // 更新时如果cordova.file.dataDirectory有相同文件，替换相同文件
//   // 更新时更改文件名
//   // 更新对应的workinstructions中的executeresults中的photos
//   resolve(pictures)
// }

// function onCameraError(err) {

// }

export default pickPhoto
